package fischl.log;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;

public final class SysoutLogs {
  public static Log.Provider provider = new Log.Provider() {
    @Override
    public Log getLog(String name) {
      return new SysoutLog(name);
    }
  };

  public static void init() {
    LogFactory.setProvider(provider);
  }

 public static class SysoutLog implements Log {
   private final String tag;
   private final SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss", Locale.CHINA);

   public SysoutLog(String tag) {
     this.tag = tag;
   }

   @Override
   public void i(String message) {
     logLine("I", message);
   }

   @Override
   public void w(String message) {
     logLine("W", message);
   }

   @Override
   public void e(String message) {
     logLine("E", message);
   }

   @Override
   public void e(Throwable t) {
     e("", t);
   }

   @Override
   public void e(String message, Throwable t) {
     logLine("E", message);
     ByteArrayOutputStream out = new ByteArrayOutputStream();
     try {
       PrintStream p = new PrintStream(out, true, "UTF-8");
       t.printStackTrace(p);
       p.flush();
       log(out.toString("UTF-8"));
     } catch (Exception e) {
       //ignored
     }
   }

   private void logLine(String level, String message) {
     String threadName = Thread.currentThread().getName();
     if (threadName.length() > 8) {
       threadName = threadName.substring(0, 6) + "..";
     } else {
       char[] blankArr = new char[8 - threadName.length()];
       Arrays.fill(blankArr, ' ');
       threadName = threadName + new String(blankArr);
     }

     String logTime = format.format(new Date());
     String tag = this.tag;
     StringBuilder output = new StringBuilder(level).append("[").append(logTime).append("|").append(threadName).append("]").append(tag).append(": ").append(message);
     log(output.toString());
   }

   @Override
   public void i(String message, Object... args) {
     logLine("I", replaceArgs(message, args));
   }


   @Override
   public void w(String message, Object... args) {
     logLine("W", replaceArgs(message, args));
   }


   @Override
   public void e(String message, Object... args) {
     logLine("E", replaceArgs(message, args));
   }

   static String replaceArgs(String message, Object... args) {
     if (args == null) return message;
     String[] argsStrings = new String[args.length];
     for (int i = 0; i < args.length; i++) {
       argsStrings[i] = String.valueOf(args[i]);
     }
     message = message.replaceAll("\\{\\}", "%s");
     return String.format(message, (Object[]) argsStrings);
   }

   private void log(String msg) {
     System.out.println(msg);
   }
 }
}
